<template>
  <div class="producDetail">
    <div>
      <!--      <el-dropdown style="margin-bottom: 10px;margin: 0 10px">-->
      <!--        <el-button type="primary" size="mini">审核<i class="el-icon-arrow-down el-icon&#45;&#45;right" /></el-button>-->
      <!--        <el-dropdown-menu slot="dropdown">-->
      <!--          <el-dropdown-item @click.native="audit(1)">审核(生产用料单)</el-dropdown-item>-->
      <!--          <el-dropdown-item @click.native="audit(2)">反审核(生产用料单)</el-dropdown-item>-->
      <!--          <el-dropdown-item @click.native="audit1(1)">审核(委外用料订单)</el-dropdown-item>-->
      <!--          <el-dropdown-item @click.native="audit1(2)">反审核(委外用料订单)</el-dropdown-item>-->
      <!--        </el-dropdown-menu>-->
      <!--      </el-dropdown>-->
      <!--      <el-button type="primary" style="width: 60px;margin-bottom: 10px" size="mini" @click="pushDown()">下推</el-button>-->
      <!--      <el-button type="danger" size="mini" @click="delPublic()">{{ $t('shop.delete') }}生产</el-button>-->
      <!--      <el-button type="danger" size="mini" @click="delPublicOut()">{{ $t('shop.delete') }}委外</el-button>-->
      <el-button size="mini" @click="queryTPrdMoDetails()">{{ $t('btn.reload') }}</el-button>
      <el-button type="warning" size="mini" @click="handleExport()">{{ $t('btn.toExcel') }}</el-button>
      <!--      <el-button v-if="fworkshop==='餐椅软体部'" type="warning" size="mini" @click="queryReportrt()">软体套打</el-button>-->
      <!--      <el-button v-if="fworkshop==='餐椅包装部'" type="warning" size="mini" @click="queryReportbz()">包装套打</el-button>-->
      <!--      <el-button v-if="fworkshop==='餐椅五金部'" type="warning" size="mini" @click="queryReportwj()">五金套打</el-button>-->
    </div>
    <el-tabs v-model="activeName">
      <el-tab-pane :label="$t('market.info')" name="first">
        <el-form
          ref="purchaseRef"
          class="proForm"
          :model="production"
          label-width="100px"
        >
          <el-form-item :label="$t('market.marketState')">
            <el-tag :type="production.stateColor">{{ production.fdocumentStatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.moSubState')">
            <el-tag :type="production.stateColors">{{ production.moSubFdocumentStatus }}</el-tag>
          </el-form-item>
          <el-form-item :label="$t('market.order')">
            <el-input v-model.trim="production.fbillNo" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.placedate')">
            <el-input v-model.trim="production.fdate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.cust')">
            <el-input v-model.trim="production.customer" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.deliveryDate')">
            <el-input v-model.trim="production.fdeliveryDate" disabled />
          </el-form-item>
          <el-form-item :label="$t('market.paezText1')">
            <el-input v-model.trim="production.fpaezText" disabled />
          </el-form-item>
        </el-form>
        <el-tabs v-model="active">
          <el-tab-pane class="tabsOne" :label="$t('market.detailInfo')" name="first">
            <jc-table
              :table-data="tableData"
              :table-header="tableHeard"
              :table-height="tableHeight"
              :highlight="false"
              serial
              @selectionChange="handleSelectAll"
            >
              <el-table-column type="selection" width="30px" sortable="true" align="center" />
              <template v-slot:btnState="col">
                <el-link type="primary" @click="materialsDetail(col.scope.row)">{{ col.scope.row.userNo }}</el-link>
              </template>
              <!--订单类型-->
              <template v-slot:btnSlot="col">
                <span v-if="col.scope.row.ftype === 0">{{ $t('menu.collect') }}<!--生产订单--></span>
                <span v-if="col.scope.row.ftype === 1">{{ $t('menu.productionPicking') }}<!--委外订单--></span>
              </template>
              <!--表头按钮 计划开工时间-->
              <template v-slot:header>
                {{ $t('market.planfinishDate') }}<!--计划完工时间-->
                <el-button type="primary" size="mini" @click="editDate">{{ $t('market.batchEdit') }}<!--批量修改--></el-button>
              </template>
              <template v-slot:billSlot="col">
                <el-date-picker
                  v-model="col.scope.row.fplanfinishDate"
                  type="date"
                  value-format="yyyy-MM-dd"
                  style="width: 130px"
                  size="mini"
                  :disabled="isDisabled"
                  @change="fplanfinish(col.scope.row)"
                />
              </template>
              <!--操作-->
              <template v-slot:btnStates="col">
                <el-dropdown size="mini" split-button type="warning" trigger="click" placement="bottom" @click="printing(col.scope.row,'1')">
                  {{ $t('menu.metals') }}<!--套打-->
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item @click.native="printing(col.scope.row,'1')">{{ $t('market.tong') }}<!--通用--></el-dropdown-item>
                    <el-dropdown-item @click.native="printing(col.scope.row,'2')">{{ $t('market.lian') }}<!--连续--></el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </template>
            </jc-table>
          </el-tab-pane>
        </el-tabs>
      </el-tab-pane>
    </el-tabs>
    <el-dialog
      v-dialogDrag
      :title="$t('market.checkBill')"
      model
      :visible.sync="isdanjuDialog"
      :close-on-click-modal="false"
      width="600px"
      top="5vh"
      center
    >
      <div style="text-align: center;height: 100px;line-height: 30px">
        <el-radio-group v-model="orderLX">
          <el-radio v-for="item in receipts" :key="item" :label="item">{{ item }}</el-radio>
        </el-radio-group>
        <br>
      <!--        <el-radio-group v-model="orderLX">-->
      <!--          <el-radio v-for="item in outReceipts" :key="item" :label="item">{{ item }}</el-radio>-->
      <!--        </el-radio-group>-->
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isdanjuDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="pushDownOrder()">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!--   批量修改时间  -->
    <el-dialog
      v-dialogDrag
      :title="$t('market.batchEditDate')"
      model
      :visible.sync="iseditDateDialog"
      :close-on-click-modal="false"
      width="300px"
      top="5vh"
      center
    >
      <span style="margin-right: 20px">{{ $t('market.fdate') }}</span>
      <el-date-picker
        v-model="batchEditDate"
        type="date"
        value-format="yyyy-MM-dd"
        style="width: 180px"
        size="mini"
      />
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="iseditDateDialog = false">{{ $t('btn.cancel') }}</el-button>
        <el-button size="mini" type="primary" @click="batchEdit">{{ $t('btn.confirm') }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  queryTPrdMoDetails,
  updatePlanFinishDate, updatePlanFinishDates,
  auditPrdPpboms, unauditPrdPpboms,
  auditSubPpboms, unauditSubPpboms,
  pushToPrdInstock, pushToPrdUninstock,
  pushToSubUninstock, delPrdMos, delPrdMosOut
} from '@/api/production/productionList'
import { toMxAmina, moSubToMxAmina } from '@/components/ToMxamineState'
import { export_json_to_excel, formatJson } from '@/utils/Export2Excel'

export default {
  name: 'ProductionDetails',
  props: {
    msg: {
      type: String,
      default: ''
    }, fdeptId: {
      type: [Number, String],
      default: 0
    }, dh: {
      type: [Number, String],
      default: ''
    }, fworkshop: {
      type: [Number, String],
      default: ''
    }
  },

  data() {
    return {
      orderLX: this.$t('menu.proStirageOrder'),
      receipts: [this.$t('menu.proStirageOrder'), this.$t('menu.proTuiStockDetail')], // 生产 '生产入库单''生产退库单'
      // outReceipts: ['委外退库单'], // 委外
      isdanjuDialog: false, // 选择单据
      iseditDateDialog: false, // 批量修改时间
      activeName: 'first',
      active: 'first',
      production: {
        fid: '',
        fdate: '',
        fbillNo: '',
        fpaezText: '',
        customer: '',
        fdocumentStatus: '',
        fdeliveryDate: ''
      },
      isDisabled: false,
      batchEditDate: '', // 批量修改时间
      dialogBol: true,
      deleteBol: true,
      downSW: '', // 弹窗单选数据
      selData: [], // 挂起
      downData: [], // 下推数据
      storageData: [], // 下推入库
      tableHeight: '60vh',
      details2: [],
      tableData: [],
      tableHeard: [
        { label: this.$t('market.salOrder'), type: 'btn', prop: 'ftype1', bag: 'redBag', width: '80' },
        { label: this.$t('market.userNo'), type: 'state', prop: 'userNo', minWidth: '130px' },
        { label: this.$t('market.fmaterial'), prop: 'fnumber', minWidth: '100' },
        { label: this.$t('market.fmodel'), prop: 'fmodel' },
        { label: this.$t('shop.fspecificaTion'), prop: 'fspecificaTion' },
        { label: this.$t('market.fdescripTion'), prop: 'fdescripTion', minWidth: '200px' },
        { label: this.$t('market.dept'), prop: 'fdept' },
        { label: this.$t('market.funit'), prop: 'funitName', width: '80' },
        { label: this.$t('market.fqty'), prop: 'fqty', width: '80' },
        { label: this.$t('market.completeQty'), prop: 'fcompleteQty', width: '80' },
        { label: this.$t('market.readyQty'), prop: 'freadyQty', width: '80' },
        { label: this.$t('market.busineState'), prop: 'fstatus', width: '80' },
        { label: this.$t('market.planstartDate'), prop: 'fplanstartDate' },
        { label: this.$t('market.planfinishDate'), type: 'bill', prop: 'fplanfinishDate', minWidth: '160px' },
        { label: this.$t('market.proFbillno'), prop: 'fbillNo' },
        { label: this.$t('market.handle'), type: 'states', minWidth: '160px' }
      ]
    }
  },
  watch: {
    msg() {
      if (this.msg) {
        this.queryTPrdMoDetails()
      }
    },
    fdeptId() {
      this.queryTPrdMoDetails()
    },
    dh() {
      this.queryTPrdMoDetails()
    }
  },
  created() {
    if (this.$route.params.id) {
      this.queryTPrdMoDetails()
    }
    this.tableHeight = window.innerWidth > 1440 ? 'calc(100vh - 320px)' : '60vh'
  },
  methods: {
    // 导出表格-生产订单汇总列表
    handleExport() {
      require.ensure([], () => {
        const tHeader = this.tableHeard.map((res) => {
          return res.label
        })
        const filterVal = this.tableHeard.map((res) => {
          return res.prop
        })
        if (this.tableData.length <= 0) {
          this.$message.warning('没有导出数据')
        } else if (this.val && this.val.length > 0) {
          const list = this.val.map(res => {
            if (res.ftype === 0) {
              res.ftype1 = '生产订单'
            } else {
              res.ftype1 = '委外订单'
            }
            if (res.fissuspend === '0') {
              res.fissuspends = '未挂起'
            } else {
              res.fissuspends = '已挂起'
            }
            return res
          })
          const data = formatJson(filterVal, list)
          export_json_to_excel(tHeader, data, '生产订单汇总列表')
        } else {
          queryTPrdMoDetails({
            fbillNo: this.$route.params.id || this.msg,
            fdeptId: this.fdeptId,
            dh: this.dh
          }).then(res => {
            if (res.code === 0) {
              const list = res.data.details.map(res => {
                if (res.ftype === 0) {
                  res.ftype = '生产订单'
                } else {
                  res.ftype = '委外订单'
                }
                if (res.fissuspend === '0') {
                  res.fissuspend = '未挂起'
                } else {
                  res.fissuspend = '已挂起'
                }
                return res
              })
              const data = formatJson(filterVal, list)
              export_json_to_excel(tHeader, data, '生产订单汇总列表')
            } else {
              this.$confirm(res.message, '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'error'
              })
            }
          })
        }
      })
    },
    async queryTPrdMoDetails() {
      const DATA = {
        fbillNo: this.$route.params.id || this.msg,
        fdeptId: this.fdeptId,
        dh: this.dh
      }
      if (!DATA.fbillNo) {
        return false
      }
      const { data: RES } = await queryTPrdMoDetails(DATA)
      this.production = toMxAmina(RES)
      this.production = moSubToMxAmina(RES)
      this.isDisabled = this.production.fdocumentStatus === this.$t('market.state1') ||
        this.production.fdocumentStatus === this.$t('market.state2')
      this.tableData = RES.details
    },
    // 全选
    handleSelectAll(val) {
      if (val) {
        this.details2 = []
        this.batchList = []
        this.selectVal = []
        this.val = val
        this.val.forEach(item => {
          this.details2.push({
            ftype: item.ftype,
            fbillNo: item.fbillNo,
            fids: item.fids
          })
          item.fbillNo && this.selectVal.push(item.userNo)
          this.batchList.push({
            ftype: item.ftype,
            fentryId: item.fentryId
          })
        })
      }
    },
    // 下推弹窗
    pushDown() {
      this.fentryData = []
      this.fidsData = []
      if (!this.val) {
        this.$message.warning('请选择数据!')
        return
      }
      for (const item in this.val) {
        if (this.val[item].fissuspend === '1') {
          this.dialogBol = false
          this.$message.warning('物料编码' + this.val[item].fnumber + '行数据已挂起, 不能下推!')
          return
        } else {
          this.dialogBol = true
        }
        if (this.val[0].ftype !== this.val[item].ftype) {
          this.$message.warning('生产和委外订单不能同时下推!')
          return
        }
        if (this.val[0].ftype === 1 && this.val[0].fdept !== this.val[item].fdept) {
          this.$message.warning('委外订单下推,供应商必须相同!')
          return
        }
        // 下推数据
        this.fentryData.push(this.val[item].fentryId)
        this.fidsData.push(this.val[item].fid)
      }
      this.fidsData = Array.from(new Set(this.fidsData))
      this.isdanjuDialog = true
    },
    // 下推
    pushDownOrder() {
      const DATA = {
        SoucrceIds: this.fidsData,
        EntryIds: this.fentryData
      }
      if (this.orderLX === this.$t('menu.proStirageOrder')) {
        pushToPrdInstock(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/proStirageOrder/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === this.$t('menu.proTuiStockDetail')) {
        pushToPrdUninstock(DATA).then(res => {
          if (res.code === 0) {
            this.$router.push({
              path: `/proTuiStockDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
          }
        })
      } else if (this.orderLX === '委外退库单') {
        const DATA = {
          SoucrceIds: this.fidsData,
          EntryIds: this.fentryData
        }
        pushToSubUninstock(DATA).then(res => {
          if (res.code === 0) {
            this.$message({ showClose: true, message: res.message, type: 'success' })
            this.$router.push({
              path: `/outTuiStockDetail/${res.data.fid}`
            })
            this.isdanjuDialog = false
          } else {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              type: 'error'
            })
          }
        })
      }
    },
    // 修改
    materialsDetail(ev) {
      const id = ev.userNo
      if (ev.ftype === 0) { // 生产
        if (this.msg) {
          this.$emit('userNo', id, 0)
        } else {
          this.$router.push({ path: `/productionEdit/${id}` })
        }
      } else { // 委外
        if (this.msg) {
          this.$emit('userNo', id, 1)
        } else {
          this.$router.push({ path: `/productionOutEdit/${id}` })
        }
      }
    },
    // 套打
    printing(en, ev) {
      if (ev === '1') {
        this.$router.push({
          path: `/proGeneralOrd/${en.fbillNo}`
        })
      } else {
        this.$router.push({
          path: `/proSuccessionOrd/${en.fbillNo}`
        })
      }
    },
    // 删除 - 委外
    delPublicOut() {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const DATA = { Numbers: [this.production.fbillNo] }
        delPrdMosOut(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          // 关闭当前页面
          this.$store.dispatch('tagsView/guanbi', this.$route)
          this.$router.push({ path: '/outOrderList' })
          this.$message({ showClose: true, message: res.message, type: 'success' })
        })
      })
    },
    // 删除 -生产订单
    delPublic() {
      this.$confirm('此操作将永久删除该订单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const DATA = { Numbers: [this.tableData[0].fbillNo] }
        delPrdMos(DATA).then(res => {
          if (res.code !== 0) {
            this.$confirm(res.message, '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'error'
            })
            return
          }
          this.$message({
            showClose: true,
            message: res.message,
            type: 'success'
          })
        })
      })
    },
    // 改变时间
    fplanfinish(ev) {
      const DATA = {
        fplanfinishDate: ev.fplanfinishDate,
        fentryId: ev.fentryId,
        ftype: ev.ftype
      }
      updatePlanFinishDate(DATA).then(res => {
        if (res.code === 0) {
          this.queryTPrdMoDetails()
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 公共函数
    toExamineFun(api) {
      const DATA = { Numbers: this.selectVal }
      api(DATA).then(res => {
        if (res.code !== 0) {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
          return
        }
        this.queryTPrdMoDetails()
        this.innerHTM = ''
        res.data.forEach(res => {
          this.innerHTM += '<div>' + res + '</div>'
        })
        this.$notify.warning({
          title: '提示',
          message: this.innerHTM,
          duration: 3000, offset: 50,
          dangerouslyUseHTMLString: true
        })
      })
    },
    // 审批 生产用料
    async audit(ev) {
      const api = ev === 1 ? auditPrdPpboms : unauditPrdPpboms
      this.toExamineFun(api)
    },
    //  审批 委外用料
    async audit1(ev) {
      const api = ev === 1 ? auditSubPpboms : unauditSubPpboms
      this.toExamineFun(api)
    },
    // 批量修改时间
    editDate() {
      this.iseditDateDialog = true
    },
    batchEdit() {
      if (this.batchList && this.batchList.length > 0) {
        this.batchList.map(res => {
          res.fplanfinishDate = this.batchEditDate
        })
      } else {
        this.$message.warning('请选择数据')
        return
      }
      const DATA = {
        list: this.batchList
      }
      updatePlanFinishDates(DATA).then(res => {
        if (res.code === 0) {
          this.batchList = []
          this.batchEditDate = ''
          this.iseditDateDialog = false
          this.queryTPrdMoDetails()
          this.$message({ showClose: true, message: res.message, type: 'success' })
        } else {
          this.$confirm(res.message, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error'
          })
        }
      })
    },
    // 软体
    queryReportrt() {
      this.$router.push({ path: '/rheid1', query: {
        fbillNo: this.production.fbillNo
      }})
    },
    // 包装
    queryReportbz() {
      this.$router.push({ path: '/packaging1', query: {
        fbillNo: this.production.fbillNo
      }})
    },
    // 五金
    queryReportwj() {
      this.$router.push({ path: '/metals1', query: {
        fbillNo: this.production.fbillNo
      }})
    }
  }
}
</script>
<style lang="scss" scope>
.producDetail {
  @include listBom;
  .el-tabs {
    .el-table tbody tr:hover > td {
      background-color: transparent;
    }

    .el-form {
      display: flex;
      flex-wrap: wrap;
      height: 100px;
      overflow: auto;
      .el-input .el-input__inner {
        height: 30px;
        line-height: 30px;
        padding: 0 15px;
      }

      .el-form-item {
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        height: 35px;
        width: 275px;
        min-width: 246px;
        margin-bottom: 0;

        .el-date-editor.el-input {
          width: 100% !important;
        }

        .el-select {
          width: 100%;
        }
      }
    }
  }
}
</style>
